package com.stu.day17;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zy
 * @date 2025/2/18 18:00
 */
public class ConditionDemo {
    public static void main(String[] args) {
        ConditionDemo demo = new ConditionDemo();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                demo.printUpper();
            }
        });
        Thread t2 = new Thread(() -> demo.printLower());
        Thread t3 = new Thread(demo::printNum);

        t1.start();
        t2.start();
        t3.start();
    }

    private final Lock lock = new ReentrantLock();
    //创建三个队列,每个队列对应不同的任务
    private final Condition c1 = lock.newCondition();//负责打印大写字母
    private final Condition c2 = lock.newCondition();//负责打印小写字母
    private final Condition c3 = lock.newCondition();//负责打印数字

    //count=0 执行c1   count=1 执行c2  count2执行c3
    private int count;

    public void printUpper() {
        for (char i = 'A'; i <= 'Z'; i++) {
            try {
                lock.lock();
                if (count != 0) {
                    //让此线程进入到等他阻塞的状态,必须要被其他线程唤醒
                    c1.await();
                }
                System.out.print(i + " ");
                count = 1;
                //唤醒指定的小写字母的线程
                c2.signal();

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    }

    public void printLower() {
        for (char i = 'a'; i <= 'z'; i++) {
            try {
                lock.lock();
                if (count != 1) {
                    //让此线程进入到等他阻塞的状态,必须要被其他线程唤醒
                    c2.await();
                }
                System.out.print(i + " ");
                count = 2;
                //唤醒指定的数字的线程
                c3.signal();

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    }

    public void printNum() {
        for (int i = 1; i <= 26; i++) {
            try {
                lock.lock();
                if (count != 2) {
                    //让此线程进入到等他阻塞的状态,必须要被其他线程唤醒
                    c3.await();
                }
                System.out.print(i + " ");
                count = 0;
                //唤醒指定的大写字母的线程
                c1.signal();

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    }
}